package com.springboot.love.service.impl;

import com.springboot.love.dao.UserDao;
import com.springboot.love.entity.Post;
import com.springboot.love.entity.User;
import com.springboot.love.service.UserService;
import com.springboot.love.utils.PageUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;


    /**
     * 查询多条数据
     *
     * @param pageUtil 查询起始位置
     * @return 对象列表
     */
    @Override
    public List<User> queryAllByTime(PageUtil pageUtil) {
        return this.userDao.queryAllByTime(pageUtil);
    }

    /**
     * @return 数据数量
     */
    @Override
    public int queryTotalByTime() {
        return this.userDao.queryTotalByTime();
    }

    /**
     * 检查密码是否合法
     * @param userId 当前用户id
     * @param pass 要修改的密码
     * @param repass 重新输入的密码
     * @return 1:新密码和重复密码不同
     *          2：当前密码错误
     *          3：新密码与当前密码相同
     *          4：密码不符合要求（6到16个字符）
     */
    @Override
    public int checkPass(String userId, String pass, String repass) {
        SimpleHash nowpassSh = new SimpleHash("MD5", pass, userDao.queryById(Integer.parseInt(userId)).getSalt(),5);
        String password=userDao.queryById(Integer.parseInt(userId)).getPassword();
        if (!pass.equals(repass)){
            return 1;
        }else if (nowpassSh.toHex().equals(password)){
            return 3;
        }else if (pass.length()<6||pass.length()>16){
            return 4;
        }else {
            return 0;
        }
    }
    /**
     * 修改密码
     * @param pass
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modifyPass(String userId, String pass) {
        String salt= UUID.randomUUID().toString();
        SimpleHash passSh=new SimpleHash("md5",pass,salt,5);
        User user = new User();
        user.setUserId(Integer.parseInt(userId));
        user.setSalt(salt);
        user.setPassword(passSh.toHex());
        int update = userDao.updateById(user);
        if (update>0){
            return true;
        }else {
            return false;
        }
    }
}
